
package com.jf.cloud.live.controller.multishop;

import cn.hutool.core.util.StrUtil;
import com.jf.cloud.api.product.feign.SpuFeignClient;
import com.jf.cloud.common.constant.StatusEnum;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.product.vo.SpuVO;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.CharUtil;
import com.jf.cloud.live.param.LiveUsableNumParam;
import com.jf.cloud.live.constant.LiveConstant;
import com.jf.cloud.live.constant.LiveInterfaceType;
import com.jf.cloud.live.constant.LiveProdStatusType;
import com.jf.cloud.live.dto.LiveProdStoreDTO;
import com.jf.cloud.live.model.LiveProdStore;
import com.jf.cloud.live.model.LiveRoomProd;
import com.jf.cloud.live.service.LiveLogService;
import com.jf.cloud.live.service.LiveProdStoreService;
import com.jf.cloud.live.service.LiveRoomProdService;
import com.jf.cloud.live.util.WxImageUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.Operation;
import ma.glasnost.orika.MapperFacade;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 直播商品
 *
 * @author zz
 * @date 2022-08-17 17:09:06
 */
@RestController("multishopLiveProdStoreController")
@RequestMapping("/m/live_prod_store")
@Tag(name = "商家端直播间商品库接口")
public class LiveProdStoreController {

    @Autowired
    private LiveProdStoreService liveProdStoreService;
    @Autowired
    private LiveLogService liveLogService;
    @Autowired
    private WxImageUtil wxImageUtil;
    @Autowired
    private LiveRoomProdService liveRoomProdService;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private SpuFeignClient spuFeignClient;


    @GetMapping("/page")
    @Operation(summary = "获取直播商品列表" , description = "分页获取直播商品列表")
    public ServerResponseEntity<PageVO<LiveProdStore>> page(@Valid PageDTO pageDTO, @ParameterObject LiveProdStoreDTO liveProdStoreDTO) {
        liveProdStoreDTO.setShopId(AuthUserContext.get().getTenantId());
        PageVO<LiveProdStore> liveProdStorePage = liveProdStoreService.page(pageDTO, liveProdStoreDTO);
        return ServerResponseEntity.success(liveProdStorePage);
    }

    @GetMapping("/info/{liveProdStoreId}")
    @Operation(summary = "获取直播商品" , description = "根据liveProdStoreId获取直播商品")
    public ServerResponseEntity<LiveProdStore> getByLiveProdStoreId(@ParameterObject @PathVariable("liveProdStoreId") Long liveProdStoreId) {
        LiveProdStore liveProdStore = liveProdStoreService.getByLiveProdStoreId(liveProdStoreId);
        if (!Objects.equals(AuthUserContext.get().getTenantId(), liveProdStore.getShopId())) {
            throw new LuckException(ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED));
        }
        if (Objects.nonNull(liveProdStore.getProdId())) {
            ServerResponseEntity<SpuVO> spuResponse = spuFeignClient.getById(liveProdStore.getProdId());
            SpuVO spu = spuResponse.getData();
            if (spuResponse.isSuccess() && spu != null) {
                liveProdStore.setPic(spu.getMainImgUrl());
                liveProdStore.setProdName(spu.getName());
                liveProdStore.setOriProdType(spu.getSpuType());
            }
        }
        return ServerResponseEntity.success(liveProdStore);
    }

    @PostMapping
    @Operation(summary = "保存直播商品" , description = "保存直播商品")
    public ServerResponseEntity<Void> save(@Valid @RequestBody LiveProdStoreDTO liveProdStoreDTO) {
        LiveProdStore liveProdStore = mapperFacade.map(liveProdStoreDTO, LiveProdStore.class);
        if (CharUtil.length(liveProdStore.getName()) < LiveConstant.PROD_NAME_MIN_LENGTH
                || CharUtil.length(liveProdStore.getName()) > LiveConstant.PROD_NAME_MAX_LENGTH) {
            // 名称长度非法,最少3个汉字或者6个字符、最大14个汉字！
            throw new LuckException("名称长度非法,最少3个汉字或者6个字符、最大14个汉字！");
        }
        if (StrUtil.isBlank(liveProdStore.getUrl())) {
            throw new LuckException("请选择商品");
        }
        liveProdStore.setShopId(AuthUserContext.get().getTenantId());
        Date date = new Date();
        liveProdStore.setCreateTime(date);
        liveProdStore.setStatus(LiveProdStatusType.NO_EXAMINE.value());
        liveProdStore.setUpdateTime(date);
        liveProdStore.setVerifyTime(null);
        liveProdStore.setGoodsId(null);
        liveProdStore.setSuccessTime(null);
        liveProdStore.setLiveProdStoreId(null);
        liveProdStoreService.save(liveProdStore);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "更新直播商品" , description = "更新直播商品")
    public ServerResponseEntity<Void> update(@Valid @RequestBody LiveProdStoreDTO liveProdStoreDTO) throws WxErrorException {
        LiveProdStore liveProdStore = mapperFacade.map(liveProdStoreDTO, LiveProdStore.class);
        if (CharUtil.length(liveProdStore.getName()) < LiveConstant.PROD_NAME_MIN_LENGTH || CharUtil.length(liveProdStore.getName()) > LiveConstant.PROD_NAME_MAX_LENGTH) {
            throw new LuckException("名称长度非法,最少3个汉字或者6个字符、最大14个汉字！");
        }
        if (!Objects.equals(liveProdStore.getShopId(), AuthUserContext.get().getTenantId())) {
            // 没有权限进行操作
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        LiveProdStore dbProd = liveProdStoreService.getByLiveProdStoreId(liveProdStoreDTO.getLiveProdStoreId());
        if (Objects.equals(LiveProdStatusType.EXAMINING.value(), dbProd.getStatus())) {
            // 商品正在审核中，无法进行修改
            throw new LuckException("商品正在审核中，无法进行修改");
        }
        liveProdStore.setUpdateTime(new Date());
        liveProdStoreService.updateWxLiveProdById(liveProdStore);
        return ServerResponseEntity.success();
    }


    @PutMapping("/submitVerify")
    @Operation(summary = "提交审核")
    public ServerResponseEntity<Boolean> submitVerify(@RequestBody LiveProdStore liveProdStore) {
        liveProdStore = liveProdStoreService.getByLiveProdStoreId(liveProdStore.getLiveProdStoreId());
        if (!Objects.equals(liveProdStore.getShopId(), AuthUserContext.get().getTenantId())) {
            // 没有权限进行操作
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        if (Objects.equals(LiveProdStatusType.EXAMINING.value(), liveProdStore.getStatus())) {
            // 已提交审核
            throw new LuckException("已提交审核");
        }
        ServerResponseEntity<SpuVO> spuResponse = spuFeignClient.getById(liveProdStore.getProdId());
        SpuVO spu = spuResponse.getData();
        if (spuResponse.isSuccess() && (Objects.isNull(spu) || Objects.equals(spu.getStatus(), StatusEnum.DELETE.value()))) {
            // 当前直播商品关联的商品已被删除
            throw new LuckException("当前直播商品关联的商品不存在或已被删除");
        }
        boolean b = liveProdStoreService.submitVerify(liveProdStore);
        return ServerResponseEntity.success(b);
    }

    @DeleteMapping("/{liveProdStoreId}")
    @Operation(summary = "删除直播商品" , description = "根据直播商品id删除直播商品")
    public ServerResponseEntity<Void> delete(@PathVariable("liveProdStoreId") Long liveProdStoreId) throws WxErrorException, WxErrorException {
        LiveProdStore prodStore = liveProdStoreService.getByLiveProdStoreId(liveProdStoreId);
        if(!Objects.equals(prodStore.getShopId(), AuthUserContext.get().getTenantId())){
            // 没有权限进行操作
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        liveProdStoreService.removeWxLiveProdById(liveProdStoreId, AuthUserContext.get().getTenantId());
        return ServerResponseEntity.success();
    }

    @GetMapping("/listAppleProds")
    @Operation(summary = "获取微信入库的商品列表")
    @Parameters({
            @Parameter(name = "status", description = "商品状态 0：未审核。1：审核中，2：审核通过，3：审核驳回" , required = true),
            @Parameter(name = "name", description = "商品名称" , required = true),
            @Parameter(name = "id", description = "直播间id" , required = true)
    })
    public ServerResponseEntity<PageVO<LiveProdStore>> listAppleProds(PageDTO page, @ParameterObject Integer status, @ParameterObject String name, @ParameterObject Integer id) {
        if (Objects.isNull(status)) {
            status = 2;
        }
        LiveProdStoreDTO liveProdStore = new LiveProdStoreDTO();
        liveProdStore.setStatus(status);
        liveProdStore.setName(name);
        liveProdStore.setShopId(AuthUserContext.get().getTenantId());
        List<LiveProdStore> liveProdStores = liveProdStoreService.list(liveProdStore);
        // 筛选掉已经选择的商品
        List<LiveRoomProd> prodList = liveRoomProdService.getByRoomId(id);
        // 筛选
        List<Long> filterProdStoreIds = liveProdStores.stream().filter(student -> prodList.stream().noneMatch(
                stuClass -> stuClass.getProdStoreId().equals(student.getLiveProdStoreId()))).collect(Collectors.toList()).stream().map(LiveProdStore::getLiveProdStoreId).collect(Collectors.toList());
        return ServerResponseEntity.success(liveProdStoreService.pageProdStoreByIds(page,filterProdStoreIds));
    }

    @GetMapping("/pageProdsByRoomId")
    @Operation(summary = "根据直播间id获取直播间已经选择的商品")
    @Parameter(name = "roomId", description = "直播间roomId" , required = true)
    public ServerResponseEntity<PageVO<LiveProdStore>> pageProdsByRoomId(PageDTO page, @ParameterObject Integer roomId) {
        PageVO<LiveProdStore> resPage = liveProdStoreService.pageProdByRoomId(page, roomId);
        return ServerResponseEntity.success(resPage);
    }

    @GetMapping("/getAddProdNum")
    @Operation(summary = "查询商家今日剩余可用添加直播商品、可删除商品库商品次数")
    public ServerResponseEntity<LiveUsableNumParam> getAddRoomNum() {
        LiveUsableNumParam liveNum = liveLogService.getLiveNum(AuthUserContext.get().getTenantId(), LiveInterfaceType.ADD_PROD_AUDIT);
        LiveUsableNumParam deleteLiveNum = liveLogService.getLiveNum(AuthUserContext.get().getTenantId(), LiveInterfaceType.DELETE_PROD);
        liveNum.setDeleteShopNum(deleteLiveNum.getShopNum());
        liveNum.setDeleteTotalNum(deleteLiveNum.getTotalNum());
        return ServerResponseEntity.success(liveNum);
    }

    @GetMapping("/getUpdateProdNum")
    @Operation(summary = "查询商家今日剩余可用修改直播商品次数")
    public ServerResponseEntity<LiveUsableNumParam> getUpdateProdNum() {
        return ServerResponseEntity.success(liveLogService.getLiveNum(AuthUserContext.get().getTenantId(), LiveInterfaceType.UPDATE_PROD));
    }

    @GetMapping("/getMediaId/{liveProdStoreId}")
    @Operation(summary = "根据直播间商品库id获取信息")
    @Parameter(name = "liveProdStoreId", description = "直播间商品库id" , required = true)
    public ServerResponseEntity<String> getMediaId(@ParameterObject @PathVariable("liveProdStoreId") Long liveProdStoreId) {
        LiveProdStore liveProdStore = liveProdStoreService.getByLiveProdStoreId(liveProdStoreId);
        return ServerResponseEntity.success(wxImageUtil.wxImageUpload(liveProdStore.getCoverPic()));
    }
}
